// pkgTask/pages/upload-local-files/index.js
import fileUtil from '../../../utils/fileUtil.js';
import Uploader from '../../../utils/uploader.js'
import util from '../../../utils/util.js'

// 使用测试机的IP地址，在工具设置中忽略域名校验
const MERGE_URL = util.CONST_DATA.UPLOAD_FILE_BASE_URL + '/file/mergeChunk'
const UPLOAD_URL = util.CONST_DATA.UPLOAD_FILE_BASE_URL + '/file/wxChunkUpload'

var _uploader = null

Page({

  data: {
    fileList: null,
    isUploading: false,
    curIndex: -1,
    errorSize: 0,
    successSize: 0,
    loseSize: 0,
    uploadTimeout: null,
  },

  onLoad: function (options) {
    // 设置屏幕常亮，防止屏幕熄屏导致文件上传失败
    wx.setKeepScreenOn({
      keepScreenOn: true,
    })

    this.setData({
      uploadTimeout: null
    })

    let files = fileUtil.getFiles()

    files.forEach((file) => {
      file.progress = 0
      file.status = 0 // 0待上传，1上传中，2上传失败，3文件丢失，4上传成功
    })

    // 获取本地未上传文件列表
    this.setData({
      fileList: files
    })

    console.log(this.data.fileList)

    if (this.data.fileList.length <= 0) {
      wx.showModal({
        showCancel: false,
        content: '本地已经没有待上传的文件了',
        success() {
          wx.navigateBack({
            delta: 1
          })
        }
      })
      return
    }
  },

  onUnload: function () {
    this.stopUploadTimeout()
    if (_uploader) {
      _uploader.cancel()
    }
    _uploader = null
  },

  stopUploadTimeout() {
    if (this.data.uploadTimeout != null) {
      clearTimeout(this.data.uploadTimeout)
    }
    this.setData({
      uploadTimeout: null
    })
  },

  startUploadTimeout() {
    const vm = this
    this.stopUploadTimeout()
    let tt = setTimeout(() => {
      this.setData({
        uploadTimeout: null
      })
      if (_uploader) {
        _uploader.pause()
      }
      wx.showModal({
        showCancel: true,
        cancelText: '取消上传',
        confirmText: '继续上传',
        title: '温馨提示',
        content: '若当前网络不佳，建议取消上传，待网络通畅后上传；若网络通畅，请继续上传。',
        success: res => {
          if (res.confirm) {
            vm.startUploadTimeout()
            if (_uploader) {
              _uploader.resume()
            }
          }else {
            wx.navigateBack({
              delta: 1
            })
          }
        }
      })
    }, 60000)
    this.setData({
      uploadTimeout: tt
    })
  },

  startUpload() {
    const vm = this

    if (!Uploader.isSupport()) {
      wx.showModal({
        showCancel: false,
        content: '微信基础库低于2.10.0版本，不支持分包上传文件，请升级微信APP！'
      })
      return
    }

    vm.setData({
      curIndex: -1,
      errorSize: 0,
      successSize: 0,
      loseSize: 0,
    })

    wx.getNetworkType({
      success: (res) => {
        if (res.networkType == 'wifi') {
          vm.startUploadTimeout()
          vm.uploadNextFile()
        } else {
          wx.showModal({
            showCancel: true,
            content: '当前未连接WIFI网络，确认继续上传文件？',
            success(res) {
              if (res.confirm) {
                vm.startUploadTimeout()
                vm.uploadNextFile()
              }
            }
          })
        }
      },
    })
  },

  updateLocalFileList() {
    const vm = this
    // 获取未上传成功的文件，并更新本地文件列表
    let files = vm.data.fileList.filter((file) => {
      return (file.status == 0 || file.status == 1 || file.status == 2)
    })
    files.forEach((file) => {
      file.status = 0
      file.progress = 0
    })
    fileUtil.saveFiles(files)
  },

  uploadNextFile() {
    const vm = this

    _uploader = null

    let index = vm.data.curIndex + 1

    if (index == vm.data.fileList.length) {
      vm.setData({
        isUploading: false,
      })

      if (vm.data.successSize == vm.data.fileList.length) {
        _uploader = null
        vm.stopUploadTimeout()
        wx.showModal({
          showCancel: false,
          title: '上传结果',
          content: `已成功上传所有文件（${vm.data.successSize}）`,
          success() {
            // 获取未上传成功的文件，并重置文件列表
            let files = vm.data.fileList.filter((file) => {
              return (file.status == 0 || file.status == 1 || file.status == 2)
            })
            files.forEach((file) => {
              file.status = 0
              file.progress = 0
            })
  
            fileUtil.saveFiles(files)
            vm.setData({
              fileList: files
            })
            wx.navigateBack({
              delta: 1
            })
          }
        })
      }else {
        vm.stopUploadTimeout()
        _uploader = null
        wx.showModal({
          showCancel: false,
          title: '上传结果',
          content: `成功:${vm.data.successSize} 失败:${vm.data.errorSize} 丢失:${vm.data.loseSize}`,
          success(res) {
            // 获取未上传成功的文件，并重置文件列表
            let files = vm.data.fileList.filter((file) => {
              return (file.status == 0 || file.status == 1 || file.status == 2)
            })
            files.forEach((file) => {
              file.status = 0
              file.progress = 0
            })
  
            fileUtil.saveFiles(files)
            vm.setData({
              fileList: files
            })

            if (vm.data.fileList.length <= 0) {
              wx.showModal({
                showCancel: false,
                content: '本地已经没有待上传的文件了',
                success() {
                  wx.navigateBack({
                    delta: 1
                  })
                }
              })
              return
            }
          }
        })
      }
      return
    }

    let file = vm.data.fileList[index]
    console.log("upload file ---->", file)
    file.status = 1
    vm.setData({
      isUploading: true,
      curIndex: index,
      fileList: vm.data.fileList
    })

    _uploader = new Uploader({
      tempFilePath: file.url,
      totalSize: file.size,
      fileName: file.url,     
      uploadUrl: UPLOAD_URL,
      mergeUrl: MERGE_URL,
      maxConcurrency: 10,
      chunkSize: 1024 * 1024,
      maxMemory: 100 * 1024 * 1024,
      query: {
        lbmId: file.lbmId,
        hosRecordId: file.hosRecordId,
        equRecordId: file.equRecordId,
        fileType: file.type,
      },
      header:getApp().globalData.header,
      testChunks: false,
      maxChunkRetries: 3,
      chunkRetryInterval: 100,
      timeout: 3000 * 1000,
      verbose: true,
    })

    _uploader.on('success', (res) => {
      console.log('upload success', res)
      file.status = 4
      vm.setData({
        fileList: vm.data.fileList,
        successSize: (vm.data.successSize + 1),
      })
      vm.updateLocalFileList()
      vm.uploadNextFile()
    })

    _uploader.on('fail', (res) => {
      console.log('upload fail', res)
      if (res.errMsg && res.errMsg.indexOf('not found') != -1) {
        if (file.status == 3) {
          return
        }
        file.status = 3
        vm.setData({
          fileList: vm.data.fileList,
          loseSize: (vm.data.loseSize + 1),
        })
      } else {
        if (file.status == 2) {
          return
        }
        file.status = 2
        vm.setData({
          fileList: vm.data.fileList,
          errorSize: (vm.data.errorSize + 1),
        })
      }
      vm.uploadNextFile()
    })

    _uploader.on('complete', (res) => {
      console.log('upload complete', res)
    })

    _uploader.on('progress', (res) => {
      file.progress = res.progress
      vm.setData({
        fileList: vm.data.fileList
      })
    })

    _uploader.upload()
  },

})